/**
 * constant
 */
var FACEBOOK_APP_ID = '269802973146426';
var FACEBOOK_APP_SECRET = '8d8ef033ddd6ac186e652934762b223f';

var TWITTER_CONSUMER_KEY = '8NuqZdLwJTG8ukYVTUqjTA';
var TWITTER_CONSUMER_SECRET = 'CTG2Y3nJz77ZKjsBlttwzp8Ub1NqFGYWk8mD5RguTU';

/**
 * 
 */
var crypto = require('crypto');
var algorithm = 'aes128';// or any other algorithm(eg:aes256...) supported by OpenSSL
var key = ':-)';
var cipher = crypto.createCipher(algorithm, key);  
var decipher = crypto.createDecipher(algorithm, key);

/*
var text = 'I love kittens';
var encrypted = cipher.update(text, 'utf8', 'hex') + cipher.final('hex');
var decrypted = decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8');

console.log('------text------');
console.log(text);
console.log('------encrypted------');
console.log(encrypted);
console.log('------decrypted------');
console.log(decrypted);
*/

/**
 * mysql
 */
var mysql = require('mysql');
var connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : 'root',
	database : 'aetheticshare',
	multipleStatements : true
});
connection.on('error', function(err) {
	if (!err.fatal) {
		return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
		console.log(err.stack);
		throw err;
    }
	
    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
	connection.on('error', arguments.callee);
    connection.connect();
});
connection.connect();


/**
 * passport
 */

var passport = require('passport')
  , FacebookStrategy = require('passport-facebook').Strategy
  , TwitterStrategy = require('passport-twitter').Strategy;
  
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

function findOrCreate(platform_id, display_name, platform, done){
	var user = {};
	connection.query('SELECT id FROM user WHERE platform_id = ? AND platform = ?', [platform_id, platform], function(err, result) {
		if(err){
			return done(err);
		}else{
			if(result.length==0){
				connection.query('INSERT INTO user(platform_id, display_name, platform, register_time, last_login_time) VALUES(?, ?, ?, UTC_TIMESTAMP(), UTC_TIMESTAMP())', [platform_id, display_name, platform], function(err, result){
					user.id = result.insertId;
					user.name = display_name;
					return done(null, user);
				});
			}else{
				connection.query('UPDATE user SET display_name = ?, last_login_time = UTC_TIMESTAMP() WHERE platform_id = ? AND platform = ?', [display_name, platform_id, platform]);
				user.id = result[0].id;
				user.name = display_name;
				return done(null, user);
			}
		}
	});
}

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: 'http://mapbb.net/auth/twitter/callback'
  },
  function(token, tokenSecret, profile, done) {
    console.log('twitter user profile:');
	console.log(profile);
	findOrCreate(profile.id, profile.displayName, 'twitter', done);
  }
));

passport.use(new FacebookStrategy({
    clientID: FACEBOOK_APP_ID,
    clientSecret: FACEBOOK_APP_SECRET,
    callbackURL: 'http://mapbb.net/auth/facebook/callback'
  },
  function(accessToken, refreshToken, profile, done) {
    console.log('facebook user profile:');
	console.log(profile);
	findOrCreate(profile.id, profile.displayName, 'facebook', done);
  }
));


/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 80);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('AestheticShare`s secret'));
  app.use(express.session());
  // Initialize Passport!  Also use passport.session() middleware, to support
  // persistent login sessions (recommended).
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});





app.get('/', routes.index);
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback', passport.authenticate('facebook', {successRedirect: '/auth/success', failureRedirect: '/auth/failure'}) );
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', {successRedirect: '/auth/success', failureRedirect: '/auth/failure'}) );

app.get('/auth/success', function(req, res){
	//encrypt id
	var encryptedID = cipher.update(req.user.id.toString(), 'utf8', 'hex') + cipher.final('hex');
	console.log(encryptedID);
	res.redirect('sys://cmd/close?id=' + encryptedID + '&name='+ req.user.name);
});
app.get('/auth/failure', function(req, res){
	res.redirect('sys://cmd/close?error=401');
});





http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});
